import React, { useEffect, useState } from "react";
import history from "./history";

export const RouterContext = React.createContext({});

// Router组件主要作用就是创建context，将history和location传递给子组件。
// Router组件订阅了history变化，history变化时，就通过context通知子组件并传递新的location
export const Router = ({ children }) => {
  const [location, setLocation] = useState(history.location);

  useEffect(() => {
    // 订阅history的变化。当路由发生变化时，location就会变化，进而通知组件发生变化
    const unlisten = history.listen((location) => {
      setLocation(location);
    });
    return unlisten;
  }, []);
  
  return (
    <RouterContext.Provider value={{ history, location }}>
      {children}
    </RouterContext.Provider>
  );
};
